package com.xc.hotelmgr.order.modules.mt.service;

import com.alibaba.fastjson.JSONObject;
import com.xc.hotelmgr.order.common.utils.Constant;
import com.xc.hotelmgr.order.common.utils.GeneValidateVQResponse;
import com.xc.hotelmgr.order.common.utils.XmlUtils;
import com.xc.hotelmgr.order.modules.ali.to.common.DailyInfo;
import com.xc.hotelmgr.order.modules.ali.to.validaterq.request.ValidateRQ;
import com.xc.hotelmgr.order.modules.ali.to.validaterq.response.ValidateRQResult;
import com.xc.hotelmgr.order.modules.mt.sdk.FxBaseApiRequest;
import com.xc.hotelmgr.order.modules.mt.sdk.MtClient;
import com.xc.hotelmgr.order.modules.mt.to.check.PriceModels;
import com.xc.hotelmgr.order.modules.mt.to.check.request.Check;
import com.xc.hotelmgr.order.modules.mt.to.check.response.CheckResult;
import com.xc.hotelmgr.order.modules.order.entity.DailyroomEntity;
import com.xc.hotelmgr.order.modules.order.entity.DtOrderChannelsEntity;
import com.xc.hotelmgr.order.modules.order.service.DailyroomService;
import com.xc.hotelmgr.order.modules.order.service.DtOrderChannelsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service("mtValidateService")
@Slf4j
public class MtHotelOrderCheckService {
    @Autowired
    private DailyroomService dailyroomService;

    @Autowired
    private DtOrderChannelsService dtOrderChannelsService;

    /**
     * 下单前校验(美团）
     * @param validateRQ
     * @return
     */
    public String validateRQ(ValidateRQ validateRQ){
        Check checkRequest = new Check();
        checkRequest.setHotelId(Long.valueOf(validateRQ.getHotelId()));
        checkRequest.setGoodsId(Long.valueOf(validateRQ.getRatePlanCode()));
        checkRequest.setCheckinDate(validateRQ.getCheckIn());
        checkRequest.setCheckoutDate(validateRQ.getCheckOut());
        checkRequest.setRoomNum(Integer.valueOf(validateRQ.getRoomNum()));
        Integer totaolPrice =0;
        List<DailyroomEntity> dailyroomEntities = dailyroomService.redisSelect(validateRQ.getRatePlanCode(),validateRQ.getCheckIn(),validateRQ.getCheckOut());
        for(DailyroomEntity d : dailyroomEntities){
            totaolPrice += d.getPrice();
        }
        totaolPrice = totaolPrice * Integer.valueOf(validateRQ.getRoomNum());
        checkRequest.setTotalPrice(Integer.valueOf(totaolPrice));

        FxBaseApiRequest fxBaseApiRequest = new FxBaseApiRequest();
        fxBaseApiRequest.setData(JSONObject.toJSONString(checkRequest));
        String userName = validateRQ.getAuthenticationToken().getUsername();
        DtOrderChannelsEntity dtOrderChannelsEntity =  dtOrderChannelsService.sqlSelectKey(Constant.Channel.Mt.getValue(),userName);
        if(dtOrderChannelsEntity != null) {
            fxBaseApiRequest.setAccesskey(dtOrderChannelsEntity.getAccessKey());
            fxBaseApiRequest.setSecretKey(dtOrderChannelsEntity.getSecretKey());
            fxBaseApiRequest.setPartnerId(dtOrderChannelsEntity.getSid());
        }else {
            log.error("美团：请配置飞猪接口用户名为{}的店铺对应的美团渠道账号",userName);
        }
        fxBaseApiRequest.setMethod("hotel.order.check");
        log.info("美团：下单前校验,酒店ID：{},房型ID：{},RP:{},请求报文:{}",validateRQ.getHotelId(),validateRQ.getRoomTypeId(),validateRQ.getRatePlanCode(),fxBaseApiRequest.getData());
        String mtResult ="";
        try{
            mtResult = MtClient.post(fxBaseApiRequest);
        }catch (Exception ex){
            log.error("美团：下单前校验异常,酒店ID：{},房型ID：{},RP:{},异常信息:{}",validateRQ.getHotelId(),validateRQ.getRoomTypeId(),validateRQ.getRatePlanCode(),ex.toString());
        }
        log.error("美团：下单前校验异常,酒店ID：{},房型ID：{},RP:{},返回报文:{}",validateRQ.getHotelId(),validateRQ.getRoomTypeId(),validateRQ.getRatePlanCode(),mtResult);
        CheckResult checkResponse = JSONObject.parseObject(mtResult, CheckResult.class);
        ValidateRQResult validateRQResponse = null;
        //校验成功
        if(checkResponse.getCode() == 0){
            validateRQResponse = GeneValidateVQResponse.gene(true, validateRQ.getDailyInfos(), "1");
        }else if(checkResponse.getCode() == 8) {
            //重新返回价格日历
            for (PriceModels pm : checkResponse.getPriceModels()) {
                for(DailyInfo di : validateRQ.getDailyInfos()){
                    if(StringUtils.equals(pm.getDate(),di.getDay())){
                        if(pm.getSubPrice() != null){
                            pm.setSalePrice(pm.getSalePrice() + pm.getSubPrice());
                        }
                        if(pm.getSubRatio() != null){
                            pm.setSalePrice(pm.getSalePrice() + pm.getSubRatio());
                        }
                        di.setPrice(pm.getSalePrice());
                    }
                }
            }
            validateRQResponse = GeneValidateVQResponse.gene(false, validateRQ.getDailyInfos(), "2");
            dailyroomService.updateRs(validateRQ.getRatePlanCode(),validateRQ.getDailyInfos());
        }
        return XmlUtils.toXML(validateRQResponse);
    }

}
